"use client";

import React, { useState, useEffect } from 'react';
import ComponentCard from '@/components/common/ComponentCard';
import Button from '@/components/ui/button/Button';
import Badge from '@/components/ui/badge/Badge';

interface IntelligenceReport {
  id: string;
  title: string;
  summary: string;
  type: 'transaction_analysis' | 'pattern_discovery' | 'market_intelligence' | 'risk_assessment';
  generatedAt: Date;
  confidence: number;
  tags: string[];
}

interface MarketData {
  asset: string;
  price: number;
  change24h: number;
  volume24h: number;
  marketCap: number;
}

interface MarketInsight {
  id: string;
  type: 'trend' | 'anomaly' | 'opportunity' | 'risk';
  title: string;
  description: string;
  impact: 'low' | 'medium' | 'high';
  confidence: number;
}

const MarketIntelligence: React.FC = () => {
  const [reports, setReports] = useState<IntelligenceReport[]>([]);
  const [marketData, setMarketData] = useState<MarketData[]>([]);
  const [insights, setInsights] = useState<MarketInsight[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedTimeframe, setSelectedTimeframe] = useState('24h');

  useEffect(() => {
    loadMarketData();
  }, [selectedTimeframe]);

  const loadMarketData = async () => {
    setLoading(true);
    try {
      // 模拟数据加载
      setTimeout(() => {
        setMarketData([
          {
            asset: 'ETH',
            price: 2450.32,
            change24h: -2.45,
            volume24h: 15200000000,
            marketCap: 294800000000
          },
          {
            asset: 'BTC',
            price: 43280.15,
            change24h: 1.23,
            volume24h: 22400000000,
            marketCap: 849600000000
          },
          {
            asset: 'BNB',
            price: 315.48,
            change24h: 0.87,
            volume24h: 1800000000,
            marketCap: 47200000000
          }
        ]);

        setReports([
          {
            id: '1',
            title: '以太坊大额流出分析',
            summary: '过去24小时内，检测到多笔大额ETH从交易所流出，总价值超过5000万美元。',
            type: 'transaction_analysis',
            generatedAt: new Date(),
            confidence: 0.92,
            tags: ['ETH', '交易所流出', '鲸鱼活动']
          },
          {
            id: '2',
            title: 'DeFi协议异常活动报告',
            summary: 'Uniswap和Aave协议今日交易量激增，可能与新的流动性挖矿活动相关。',
            type: 'pattern_discovery',
            generatedAt: new Date(),
            confidence: 0.85,
            tags: ['DeFi', 'Uniswap', 'Aave']
          }
        ]);

        setInsights([
          {
            id: '1',
            type: 'trend',
            title: '机构资金持续流入',
            description: '大额钱包地址持续增持，表明机构投资者信心增强',
            impact: 'high',
            confidence: 0.88
          },
          {
            id: '2',
            type: 'risk',
            title: '流动性池集中度风险',
            description: 'DEX流动性过度集中在少数池子，存在系统性风险',
            impact: 'medium',
            confidence: 0.75
          }
        ]);

        setLoading(false);
      }, 1000);
    } catch (error) {
      console.error('加载市场数据失败:', error);
      setLoading(false);
    }
  };

  const generateReport = async (type: string) => {
    try {
      const response = await fetch('/api/analysis/reports/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          type,
          params: { timeframe: selectedTimeframe }
        })
      });

      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          // 重新加载报告列表
          loadMarketData();
        }
      }
    } catch (error) {
      console.error('生成报告失败:', error);
    }
  };

  const getReportTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      transaction_analysis: '交易分析',
      pattern_discovery: '模式发现',
      market_intelligence: '市场情报',
      risk_assessment: '风险评估'
    };
    return labels[type] || type;
  };

  const getReportTypeColor = (type: string): { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" } => {
    const colors: Record<string, { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" }> = {
      transaction_analysis: { color: 'primary', variant: 'light' },
      pattern_discovery: { color: 'success', variant: 'light' },
      market_intelligence: { color: 'info', variant: 'light' },
      risk_assessment: { color: 'error', variant: 'light' }
    };
    return colors[type] || { color: 'light', variant: 'light' };
  };

  const getInsightTypeColor = (type: string): { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" } => {
    const colors: Record<string, { color: "primary" | "success" | "error" | "warning" | "info" | "light" | "dark"; variant: "light" | "solid" }> = {
      trend: { color: 'success', variant: 'light' },
      anomaly: { color: 'warning', variant: 'light' },
      opportunity: { color: 'primary', variant: 'light' },
      risk: { color: 'error', variant: 'light' }
    };
    return colors[type] || { color: 'light', variant: 'light' };
  };

  if (loading) {
    return (
      <div className="p-6">
        <div className="text-center py-12">
          <p className="text-gray-500 dark:text-gray-400">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Page Title */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Market Intelligence</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-2">Comprehensive market data analysis and intelligent insights</p>
        </div>
        
        {/* Timeframe Selection */}
        <div className="flex space-x-2">
          {['1h', '4h', '24h', '7d'].map((timeframe) => (
            <Button
              key={timeframe}
              size="sm"
              variant={selectedTimeframe === timeframe ? 'primary' : 'outline'}
              onClick={() => setSelectedTimeframe(timeframe)}
            >
              {timeframe}
            </Button>
          ))}
        </div>
      </div>

      {/* Market Data Overview */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {marketData.map((data) => (
          <ComponentCard key={data.asset} title={`${data.asset} Market Data`}>
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-gray-600 dark:text-gray-400">Price</span>
                <span className="text-xl font-bold text-gray-900 dark:text-white">
                  ${data.price.toLocaleString()}
                </span>
              </div>
              
              <div className="flex justify-between items-center">
                <span className="text-gray-600 dark:text-gray-400">24h Change</span>
                <span className={`font-medium ${
                  data.change24h >= 0 ? 'text-green-600' : 'text-red-600'
                }`}>
                  {data.change24h >= 0 ? '+' : ''}{data.change24h.toFixed(2)}%
                </span>
              </div>
              
              <div className="flex justify-between items-center">
                <span className="text-gray-600 dark:text-gray-400">24h Volume</span>
                <span className="font-medium text-gray-900 dark:text-white">
                  ${(data.volume24h / 1000000000).toFixed(1)}B
                </span>
              </div>
              
              <div className="flex justify-between items-center">
                <span className="text-gray-600 dark:text-gray-400">Market Cap</span>
                <span className="font-medium text-gray-900 dark:text-white">
                  ${(data.marketCap / 1000000000).toFixed(1)}B
                </span>
              </div>
            </div>
          </ComponentCard>
        ))}
      </div>

      {/* 智能报告生成 */}
      <ComponentCard title="生成智能报告">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Button
            onClick={() => generateReport('market_intelligence')}
            className="w-full"
          >
            市场情报报告
          </Button>
          <Button
            onClick={() => generateReport('risk_assessment')}
            className="w-full"
            variant="outline"
          >
            风险评估报告
          </Button>
          <Button
            onClick={() => generateReport('pattern_discovery')}
            className="w-full"
            variant="outline"
          >
            模式发现报告
          </Button>
          <Button
            onClick={() => generateReport('transaction_analysis')}
            className="w-full"
            variant="outline"
          >
            交易分析报告
          </Button>
        </div>
      </ComponentCard>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 最新报告 */}
        <ComponentCard title="最新报告">
          <div className="space-y-4">
            {reports.map((report) => (
              <div key={report.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="flex justify-between items-start mb-2">
                  <h4 className="font-semibold text-gray-900 dark:text-white">{report.title}</h4>
                  <Badge {...getReportTypeColor(report.type)}>
                    {getReportTypeLabel(report.type)}
                  </Badge>
                </div>
                
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{report.summary}</p>
                
                <div className="flex justify-between items-center">
                  <div className="flex space-x-2">
                    {report.tags.map((tag, index) => (
                      <Badge key={index} color="light" variant="light" size="sm">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">
                    置信度: {(report.confidence * 100).toFixed(1)}%
                  </div>
                </div>
                
                <div className="flex justify-between items-center mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
                  <span className="text-xs text-gray-500 dark:text-gray-400">
                    {report.generatedAt.toLocaleString()}
                  </span>
                  <Button size="sm" variant="outline">
                    查看详情
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </ComponentCard>

        {/* 市场洞察 */}
        <ComponentCard title="市场洞察">
          <div className="space-y-4">
            {insights.map((insight) => (
              <div key={insight.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="flex justify-between items-start mb-2">
                  <h4 className="font-semibold text-gray-900 dark:text-white">{insight.title}</h4>
                  <div className="flex space-x-2">
                    <Badge {...getInsightTypeColor(insight.type)}>
                      {insight.type}
                    </Badge>
                    <Badge 
                      color={insight.impact === 'high' ? 'error' : insight.impact === 'medium' ? 'warning' : 'success'}
                      variant="light"
                    >
                      {insight.impact}
                    </Badge>
                  </div>
                </div>
                
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{insight.description}</p>
                
                <div className="flex justify-between items-center">
                  <div className="text-xs text-gray-500 dark:text-gray-400">
                    置信度: {(insight.confidence * 100).toFixed(1)}%
                  </div>
                  <Button size="sm" variant="outline">
                    详细分析
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </ComponentCard>
      </div>

      {/* 实时监控面板 */}
      <ComponentCard title="实时监控">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
          <div className="text-center">
            <p className="text-2xl font-bold text-blue-600">1,247</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">24h大额交易</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-green-600">$2.3B</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">总交易量</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-orange-600">156</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">活跃鲸鱼</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-red-600">23</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">风险事件</p>
          </div>
        </div>
      </ComponentCard>
    </div>
  );
};

export default MarketIntelligence; 